﻿using System.ServiceModel;
using System.ServiceModel.Description;
using Ninject.Core;
using Odin.Contracts.Services;
using Odin.Execution.Client;
using Odin.Execution.Services;

using Odin.Execution.RemoteSessionManager;
using IRemoteSessionManager=Odin.Execution.RemoteSessionManager.IRemoteSessionManager;

namespace Odin.Execution.Modules
{
	public class ServiceModule : StandardModule
	{
		public static void SetAddressForService(ICommunicationObject service, string baseAddress)
		{
			var endpointProperty = service.GetType().GetProperty("Endpoint");
			if (null != endpointProperty)
			{
				var endPoint = endpointProperty.GetValue(service, null) as ServiceEndpoint;

				if (null != endPoint)
				{
					var newUri = string.Format("{0}{1}",baseAddress,endPoint.Address.Uri.AbsolutePath);
					endPoint.Address = new EndpointAddress(newUri);
				}
			}
		}

		public override void Load()
		{
			var webServer = new WebServer();
			Bind<IWebServer>().ToConstant(webServer);


			var localSessionManager = new LocalSessionManager();
			Bind<ISessionManager>().ToConstant(localSessionManager);

			var remoteSessionManager = new RemoteSessionManagerClient();
			SetAddressForService(remoteSessionManager,webServer.BaseUrl);
			Bind<IRemoteSessionManager>().ToConstant(remoteSessionManager);

			var windowService = new WindowService();
			Bind<IWindowService>().ToConstant(windowService);

			var processService = new ProcessService();
			Bind<IProcessService>().ToConstant(processService);

			var browserService = new BrowserService();
			Bind<IBrowserService>().ToConstant(browserService);

			var configuration = new Configuration();
			Bind<IConfiguration>().ToConstant(configuration);
		}
	}
}
